import Request from 'luch-request'
import { BASEURL, WHITELIST } from './constant'
import { useUserStore } from '@/store/user'



const request = new Request({
  baseURL: BASEURL,
  custom: {
    loading: true
  }
})

request.interceptors.request.use(
  (config) => { 
    if (config.custom?.loading === true) {
      uni.showLoading({
        title: '加载中...',
        mask: true
      })
    }
    const store = useUserStore()
    if (store.token && !WHITELIST.includes(config.url as string)) {
      config.header!.Authorization = `Bearer ${store.token}`
    }
    return config
  },
  (error) => {
    Promise.reject(error)
  }
)

request.interceptors.response.use(
  (res) => {
    uni.hideLoading()
    if (res.data.code !== 10000) {
      uni.showToast({
        title: res.data.message,
        icon: 'none'
      })
      return Promise.reject(res.data)
    }
    return res.data?.data
  },
  (error) => {
    uni.hideLoading()
    uni.showToast({
      title: error.data.message,
      icon: 'none'
    })
    if (error.statusCode === 401) {
      uni.reLaunch({ url: '/pages/login/index' })
    }
    Promise.reject(error)
  }
  
)


export { request}